package com.tianruan.psychological.moduls.auth.security;

import com.alibaba.fastjson.JSONObject;
import com.tianruan.psychological.common.constant.GlobalExceptionEnum;
import com.tianruan.psychological.common.response.VResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Dong
 * @Email: dong980514280@gmail.com
 * @Create: 2019-11-25 17:05
 * @PS
 */
@Component
@Slf4j
public class CustomerRestAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        VResponse<Object> result = VResponse.error(GlobalExceptionEnum.PERMISSION_DENIED);

        try {
            response.setContentType("application/json;charset=utf-8");
            response.getOutputStream().write(JSONObject.toJSONString(result).getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}